package com.wanfu.service.impl;

import com.wanfu.annotation.Log;
import com.wanfu.dao.UserAuthsMapper;
import com.wanfu.dao.UserLoginMapper;
import com.wanfu.service.UserService;
import com.wanfu.dao.UserMapper;
import com.wanfu.entity.User;
import com.wanfu.util.consts.IdentityType;
import com.wanfu.util.system.MyMD5Encoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserAuthsMapper userAuthsMapper;

    @Resource
    private UserLoginMapper userLoginMapper;

    @Override
    @Log(moduleName = "用户管理", opType = "注册")
    public User register(String mobile,String userName, String password) throws UnsupportedEncodingException {
        User user = new User();
        user.setMobile(mobile);
        user.setUserName(userName);
        if (!StringUtils.isEmpty(password)) {
            user.setPassword(MyMD5Encoder.encode(password));
        }
        userMapper.insertSelective(user);
        user = userMapper.findUserByMobile(mobile);
        return user;
    }



    @Override
    @Log(moduleName = "用户管理", opType = "登录")
    public User login(String identityType, String identifier, String credential) throws UnsupportedEncodingException {
        User user = null;
        if (IdentityType.MOBILE.equals(identityType)) {
            user = userMapper.findUserByMobile(identifier);
        }
        if (IdentityType.USER_NAME.equals(identityType)) {
            user = userMapper.findUserByUserName(identifier);
        }
        if (user != null && !user.getPassword().equals(MyMD5Encoder.encode(credential))){
            return null;
    }
        return user;
    }

    @Override
    public User findUserByMobile(String mobile) {
        return userMapper.findUserByMobile(mobile);
    }

    @Override
    public User findUserByUserName(String userName) {
        return userMapper.findUserByUserName(userName);
    }

}
